//
//  SISSConversationListViewController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/6/8.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSConversationListViewController.h"
#import "SISSChatViewController.h"
#import "SISSContactListCell.h"
#import "SISSContactSearchView.h"
#import "SISSJsonRequestNetworkingManager+Message.h"
#import "SISSTabBarController.h"

static NSString *contactListCellID = @"contactListCellID";
@interface SISSConversationListViewController ()<SISSContactSearchViewDelegate>

// 保存旋转状态(展开/折叠);
@property (strong, nonatomic)  NSMutableArray *switchArr;
/* 联系人模型数组 */
@property (strong, nonatomic) NSMutableArray<NSMutableArray<SISSContactModel *> *> *contactArr;
/* 筛选联系人模型数组 */
@property (strong, nonatomic) NSMutableArray<NSMutableArray<SISSContactModel *> *> *searchContactArr;

@end

@implementation SISSConversationListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self requestContactListData];
    
    for (int i = 0; i < 5; i++) {
        
        if (self.switchArr == nil) {
            self.switchArr = [[NSMutableArray alloc]init];
        }
        [self.switchArr addObject:@NO];
    }
    
    [self.tableView registerNib:[UINib nibWithNibName:@"SISSContactListCell" bundle:nil] forCellReuseIdentifier:contactListCellID];
 
    [self setupUI];
    
    WeakSelf
    [kSISSRefresh prepareHeaderRefresh:self.tableView loadDataBlock:^{
        kSISSRefresh.refreshType = SISSRefressTypeUpDown;
        [weakSelf requestContactListData];
    }];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
   
    [self requestContactListData];

}

- (void)messagesDidReceive:(NSArray *)aMessages {
    
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    // 2.1 系统声音
    AudioServicesPlaySystemSound(1007);
   [self requestContactListData];
}

#pragma mark - SISSContactSearchViewDelegate 收到文字改变后的筛选
- (void)textFieldTextDidchangWithTextField:(UITextField *)textField {
    
    NSString *text = textField.text ? textField.text : @"";
    
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:3];
    for (NSInteger i = 0; i < self.contactArr.count; i++) {
        NSMutableArray *arr1 = [NSMutableArray arrayWithCapacity:self.contactArr[i].count];
        for (NSInteger j = 0; j < self.contactArr[i].count; j++) {
            
            SISSContactModel *model = self.contactArr[i][j];
            
            NSString *pinyin = [NSString transformToPinyin:model.name];
            
            if ([pinyin rangeOfString:text options:NSCaseInsensitiveSearch].length >0) {
                
                [arr1 addObject:model];
            }
        }
        [arr addObject:arr1];
    }
    
    self.searchContactArr = (text !=nil && text.length) ? arr : self.contactArr;
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if ([self.switchArr[section] boolValue] == YES) {
        return self.searchContactArr[section].count;
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SISSContactListCell *cell = [tableView dequeueReusableCellWithIdentifier:contactListCellID forIndexPath:indexPath];
    
    SISSContactModel *model = self.searchContactArr[indexPath.section][indexPath.row];
    cell.contactModel = model;
    cell.contentView.backgroundColor = model.isTop ? [UIColor groupTableViewBackgroundColor] : [UIColor whiteColor];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    SISSContactModel *model = self.searchContactArr[indexPath.section][indexPath.row];
    SISSChatViewController *chatVC = [[SISSChatViewController alloc] initWithConversationChatter:model.conversationId conversationType:EMConversationTypeChat];
    [SISSPublicSingleton shared].unreadCount -= model.unreadCount;
    chatVC.contactModel = model;
    chatVC.title = model.name;
    [self.navigationController pushViewController:chatVC animated:YES];
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"dfg";
}



#pragma mark - tableView侧滑
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        [[EMClient sharedClient].chatManager deleteConversation:self.contactArr[indexPath.section][indexPath.row].conversationId isDeleteMessages:YES completion:^(NSString *aConversationId, EMError *aError) {
            
            if (!aError) {
                NSLog(@"删除联系人成功！");
                [self requestContactListData];
            } else {
                NSLog(@"删除联系人失败！");
            }
        }];
        // 1. 更新数据
        [self.searchContactArr[indexPath.section] removeObjectAtIndex:indexPath.row];
        // 2. 更新UI
        [tableView deleteRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
    }];
    
    NSString *title = self.searchContactArr[indexPath.section][indexPath.row].isTop ? @"取消置顶" : @"置顶";
    
    // 删除一个置顶按钮
    UITableViewRowAction *topRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:title handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
       BOOL isTop =  self.searchContactArr[indexPath.section][indexPath.row].isTop = !self.searchContactArr[indexPath.section][indexPath.row].isTop;
    
        if (isTop) { // 置顶
            // 1. 更新数据
            [self.searchContactArr[indexPath.section] exchangeObjectAtIndex:indexPath.row withObjectAtIndex:0];
            // 2. 更新UI
            NSIndexPath *firstIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
            [tableView moveRowAtIndexPath:indexPath toIndexPath:firstIndexPath];
            
            [tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationTop];
            
        } else { // 取消置顶
            [self requestContactListData];
        }
    }];
                                          
    topRowAction.backgroundColor = COLOR(0x8998A5);
    
    // 将设置好的按钮放到数组中返回
    return @[deleteRowAction, topRowAction];

}

- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath  API_AVAILABLE(ios(11.0)){
    
    if (@available(iOS 11.0, *)) {
        UIContextualAction *deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"删除" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
            [[EMClient sharedClient].chatManager deleteConversation:self.contactArr[indexPath.section][indexPath.row].conversationId isDeleteMessages:YES completion:^(NSString *aConversationId, EMError *aError) {
                
                if (!aError) {
                    NSLog(@"删除联系人成功！");
                    [self requestContactListData];
                } else {
                    NSLog(@"删除联系人失败！");
                }
            }];
            // 1. 更新数据
            [self.searchContactArr[indexPath.section] removeObjectAtIndex:indexPath.row];
            // 2. 更新UI
            [tableView deleteRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
        }];
        NSString *title = self.searchContactArr[indexPath.section][indexPath.row].isTop ? @"取消置顶" : @"置顶";
        
        UIContextualAction *topAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:title handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
            BOOL isTop =  self.searchContactArr[indexPath.section][indexPath.row].isTop = !self.searchContactArr[indexPath.section][indexPath.row].isTop;
            
            if (isTop) { // 置顶
                // 1. 更新数据
                [self.searchContactArr[indexPath.section] exchangeObjectAtIndex:indexPath.row withObjectAtIndex:0];
                // 2. 更新UI
                NSIndexPath *firstIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
                [tableView moveRowAtIndexPath:indexPath toIndexPath:firstIndexPath];
                
                [tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationTop];
                
            } else { // 取消置顶
                [self requestContactListData];
            }
        }];
        topAction.backgroundColor =  COLOR(0x8998A5);
        
        UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[deleteAction, topAction]];
        config.performsFirstActionWithFullSwipe = NO;
        return config;
    }
    return nil;
}

// 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 77 / 375.0 * SCREEN_WIDTH;
}

// 分区头的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50 / 375.0 * SCREEN_WIDTH;
}

// 分区尾的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 1.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320 / 375.0 * SCREEN_WIDTH, 50 / 375.0 * SCREEN_WIDTH)];
    view.backgroundColor = [UIColor whiteColor];
    // 边界线
//    UIView *borderView = [[UIView alloc]initWithFrame:CGRectMake(0, 50 / 375.0 * SCREEN_WIDTH, SCREEN_WIDTH, 0.5)];
//    borderView.backgroundColor = [UIColor yyr_colorWithHex:0xC8C7CC];
//    [view addSubview:borderView];
    // 展开箭头
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(15 / 375.0 * SCREEN_WIDTH, 19 / 375.0 * SCREEN_WIDTH, 14 / 375.0 * SCREEN_WIDTH, 12 / 375.0 * SCREEN_WIDTH)];
    imageView.image = [UIImage imageNamed:@"message_收起"];
    [view addSubview:imageView];
    // 分组名Label
    UILabel *groupLable = [[UILabel alloc]initWithFrame:CGRectMake(45 / 375.0 * SCREEN_WIDTH, 0, SCREEN_WIDTH, 50 / 375.0 * SCREEN_WIDTH)];
    NSArray *array = @[@"卖家", @"买家", @"出租方", @"租客方", @"中介"];
    groupLable.text = array[section];
    groupLable.textColor = COLOR(0x334A60);
    groupLable.font = [UIFont systemFontOfSize:16];
    [view addSubview:groupLable];
    // 每组人数
    UILabel *memberNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 50 / 375.0 * SCREEN_WIDTH - 10, 15 / 375.0 * SCREEN_WIDTH, 80 / 375.0 * SCREEN_WIDTH, 20 / 375.0 * SCREEN_WIDTH)];
    memberNumLabel.textColor = COLOR(0x334A60);
    NSString *numStr = [NSString stringWithFormat:@"（%zd）",self.searchContactArr[section].count];
    memberNumLabel.text = numStr;
    [view addSubview:memberNumLabel];
    
    view.userInteractionEnabled = YES;
    // 初始化一个手势
    UITapGestureRecognizer *myTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(openClick:)];
    // 给view添加手势
    [view addGestureRecognizer:myTap];
    view.tag = 1000 + section;
    
    CGFloat rota;
    if ([self.switchArr[section] boolValue] == NO) {
        rota = M_PI;
    } else {
        rota = M_PI + M_PI_2; // π/2
    }
    imageView.transform = CGAffineTransformMakeRotation(rota);// 箭头偏移π/2
    return view;
}

/// 展开关闭点击事件
- (void)openClick:(UITapGestureRecognizer *)sender {
    [self.view endEditing:YES];
    NSInteger section = sender.view.tag - 1000;
    if ([self.switchArr[section] boolValue] == NO) {
        [self.switchArr replaceObjectAtIndex:section withObject:@YES];
    } else {
        [self.switchArr replaceObjectAtIndex:section withObject:@NO];
    }
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
}

// tableView 上添加的自定义手势
- (void)tableViewTouchInSide{
    // ------结束编辑，隐藏键盘
    [self.view endEditing:YES];
}

#pragma mark - 加载数据
- (void)requestContactListData {
    //    EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:[SISSUserAccount shared].userName type:EMConversationTypeChat createIfNotExist:YES];
  
    NSArray<EMConversation *> *conversations = [[EMClient sharedClient].chatManager getAllConversations];

//    [[EMClient sharedClient].chatManager deleteConversations:conversations isDeleteMessages:YES completion:^(EMError *aError) {
//        
//        NSLog(@"%@",aError);
//    }];
    NSMutableArray *parameters = [NSMutableArray arrayWithCapacity:conversations.count];
    
    NSInteger unreadCount = 0;
    for (NSInteger i = 0; i < conversations.count; i++) {
        EMConversation *conversation = conversations[i];
        
        [parameters addObject:conversation.conversationId];
        unreadCount += [conversation unreadMessagesCount];
        NSLog(@"%@",conversation.conversationId);
    }
    
    [SISSPublicSingleton shared].unreadCount = unreadCount;
    
    [kJsonRequestNetworkingManager requestIMContactListWithParameters:parameters success:^(NSArray<SISSContactModel *> *contactArr) {
        
        NSMutableArray *arr1 = [NSMutableArray array];
        NSMutableArray *arr2 = [NSMutableArray array];
        NSMutableArray *arr3 = [NSMutableArray array];
        NSMutableArray *arr4 = [NSMutableArray array];
        NSMutableArray *arr5 = [NSMutableArray array];
        for (NSInteger i = 0; i < contactArr.count; i++) {
            SISSContactModel *model = contactArr[i];
            NSString *latestMessageTitle = @"";
            
            EMMessage *lastMessage = conversations[i].latestMessage;
            if (lastMessage) {
                EMMessageBody *messageBody = lastMessage.body;
                switch (messageBody.type) {
                    case EMMessageBodyTypeImage:{
                        latestMessageTitle = NSLocalizedString(@"[图片]", @"[image]");
                    } break;
                    case EMMessageBodyTypeText:{
                        // 表情映射。
                        NSString *didReceiveText = [EaseConvertToCommonEmoticonsHelper
                                                    convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
                        latestMessageTitle = didReceiveText;
                        if ([lastMessage.ext objectForKey:MESSAGE_ATTR_IS_BIG_EXPRESSION]) {
                            latestMessageTitle = @"[动画表情]";
                        }
                    } break;
                    case EMMessageBodyTypeVoice:{
                        latestMessageTitle = NSLocalizedString(@"[语音]", @"[voice]");
                    } break;
                    case EMMessageBodyTypeLocation: {
                        latestMessageTitle = NSLocalizedString(@"[位置]", @"[location]");
                    } break;
                    case EMMessageBodyTypeVideo: {
                        latestMessageTitle = NSLocalizedString(@"[视频]", @"[video]");
                    } break;
                    case EMMessageBodyTypeFile: {
                        latestMessageTitle = NSLocalizedString(@"[文件]", @"[file]");
                    } break;
                    default: {
                    } break;
                }
            }
            
            model.latestMessageStr = latestMessageTitle;
            NSDate *messageDate = [NSDate dateWithTimeIntervalInMilliSecondSince1970:(NSTimeInterval)conversations[i].latestMessage.timestamp];
//            NSString *str = [NSDate yyr_timeStampToWeChatString:conversations[i].latestMessage.timestamp];
            model.latestTimeStr = [messageDate formattedTime];
            model.conversationId = conversations[i].conversationId;
            model.unreadCount = conversations[i].unreadMessagesCount;
            switch (model.accountType) {
                case 1: // 中介
                    [arr5 addObject:model];
                    break;
                case 2: // 卖家
                    [arr1 addObject:model];
                    break;
                case 3: // 买家
                    [arr2 addObject:model];
                    break;
                case 4: // 出租方
                    [arr3 addObject:model];
                    break;
                case 5: // 租客方
                    [arr4 addObject:model];
                    break;
                    
                default:
                    break;
            }
        }
        
        self.contactArr = [NSMutableArray arrayWithArray:@[arr1, arr2, arr3, arr4, arr5]];
        self.searchContactArr = self.contactArr;
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            
            [self.tableView.mj_header endRefreshing];
            [self.tableView reloadData];
        }];
        
    } failed:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        NSLog(@"%@",error);
    }];
    
}

#pragma mark - UI
- (void)setupUI {
    
    self.view.backgroundColor = [UIColor whiteColor];
    SISSContactSearchView *searchView = [[SISSContactSearchView alloc] init];
    searchView.placeHolder = @"请输入姓名";
    searchView.delegate = self;
    [self.view addSubview:searchView];
    
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(50);
    }];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(searchView.mas_bottom);
    }];
    
    UITapGestureRecognizer *tableViewGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableViewTouchInSide)];
    tableViewGesture.numberOfTapsRequired = 1;//几个手指点击
    tableViewGesture.cancelsTouchesInView = NO;//是否取消点击处的其他action
    [self.tableView addGestureRecognizer:tableViewGesture];
}

@end
